<template>
  <div class="container">
    <!-- 顶部栏 -->
    <div class="top-header">
      <div style="font-size: 21px;">报告导出样式：</div>
      <el-select v-model="reportFlag" placeholder="导出样式" style="width: 100px;" class="filter-item">
            <el-option
              v-for="item in reportFlags"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

    </div>

    <!-- 内容区：再分左右 -->
    <div class="content-area">
      <!-- 左侧：日历 -->
      <div class="calendar-panel" @wheel.prevent="onCalendarWheel">
        <el-calendar v-model="currentDate" @select="scrollToTask">
      <template #date-cell="{ data }">
        <div
          class="date-cell"
          :class="[
            data.isSelected ? 'is-selected' : '',
            data.day === today ? 'is-today' : ''
          ]"
          @click="scrollToTask(data.day)"
        >
        <div class="date-number">{{ new Date(data.day).getDate() }}</div>
          <div class="task-count" v-if="taskCountByDate[data.day]">
            共{{ taskCountByDate[data.day] }}个任务
        </div>
        </div>
      </template>
    </el-calendar>
      </div>

      <!-- 右侧：任务列表 -->
      <div class="report-panel" ref="taskContainer">
        <div
          v-for="(tasks, date) in groupedTasks"
          :key="date"
          :id="date"
          class="task-group"
        >
          <div class="task-date">
            <span>{{ formatDisplayDate(date) }}</span>
            <span class="task-count">共 {{ tasks.length }} 个任务</span>
          </div>
          <table class="task-table">
            <tbody>
              <tr v-for="(task, index) in tasks" :key="task.inspectionTask.id">
                <td>{{ index + 1 }}</td>
                <td>{{ task.inspectionTask.taskName }}</td>
                <td>
                  <el-tag
                    v-if="task.inspectionTask.reportStatus != 'S'"
                    type="warning"
                    size="small"
                  >
                    {{ task.inspectionTask.taskStatus }}
                  </el-tag>
                  <el-button
                    v-else-if="hasPermission(authStore.permissions,5)"
                    type="success"
                    size="small"
                    @click="upload(task.inspectionTask.taskName, task.inspectionTask.id)"
                  >
                    下载报告
                  </el-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick ,watch} from 'vue';
import request from '@/utils/request';
import showMessage from '@/utils/showMessage';
import { ElMessage } from 'element-plus';
import { useReportStore } from '@/stores/reportFlag'
import type { ReportFlag, ReportFlagOption } from '@/stores/reportFlag'
import { useAuthStore } from '@/stores/user';
import { hasPermission } from '@/utils/permissionUtils';
const authStore = useAuthStore();//使用store仓库进行数据管理
const reportStore = useReportStore()
const allTask = ref([]);
const taskCountByDate = ref<Record<string, number>>({});
const groupedTasks = ref<Record<string, any[]>>({});
const taskContainer = ref<HTMLElement | null>(null);
  const reportFlag = ref<ReportFlag>(reportStore.reportFlag)
const reportFlags = ref<ReportFlagOption[]>([
  {
    value: 'diagram',
    label: '有图模式',
  },
  {
    value: 'noDiagram',
    label: '无图模式',
  },
])



const today = new Date().toISOString().split('T')[0];
const currentDate = ref(new Date());

const formatDisplayDate = (day: string) => {
  const [y, m, d] = day.split('-');
  return `${parseInt(m)}月${parseInt(d)}日`;
};
const onCalendarWheel = (event:any) => {
  const delta = event.deltaY;
  const newDate = new Date(currentDate.value);
  if (delta > 0) {
    newDate.setMonth(newDate.getMonth() + 1);
  } else {
    newDate.setMonth(newDate.getMonth() - 1);
  }
  currentDate.value = newDate;
};
const getAllTask = () => {
  request.get('/inspection/getAllInspectionTask').then((res) => {
    // 对任务列表根据 inspectionDate 倒序排序
    const sortedData = res.data.sort((a: any, b: any) => {
      const dateA = new Date(a.inspectionTask.inspectionDate).getTime();
      const dateB = new Date(b.inspectionTask.inspectionDate).getTime();
      return dateB - dateA; // 最新在前
    });

    allTask.value = sortedData;

    const countMap: Record<string, number> = {};
    const groupedMap: Record<string, any[]> = {};

    sortedData.forEach((task: any) => {
      const date = task.inspectionTask.inspectionDate;
      countMap[date] = (countMap[date] || 0) + 1;
      groupedMap[date] = groupedMap[date] || [];
      groupedMap[date].push(task);
    });

    taskCountByDate.value = countMap;
    groupedTasks.value = groupedMap;
  });
};




const upload = (name:any,id:number) => {
  ElMessage({
    message: '正在下载，请稍后',
    type: 'warning',
  })
      request.post('/inspection/downloadReport',{id}, { responseType: 'arraybuffer' }).then(res => {
        // showMessage(res)
    // 创建一个 Blob 对象，指定文件类型为 Excel
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});

    // 创建一个临时的下载链接
    const url = window.URL.createObjectURL(blob);

    // 创建一个下载链接元素
    const a = document.createElement('a');
    a.href = url;
    a.download = `${name}_Repost.docx`; // 指定下载文件的名称
    // 触发点击事件开始下载
    document.body.appendChild(a);
    a.click();

    // 下载完成后清除 URL 对象
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('下载模板失败:', error);
  });

      
  }


const scrollToTask = (date: string) => {
  const normalizedDate = new Date(date).toISOString().split('T')[0];

  nextTick(() => {
    const targetElement = document.getElementById(normalizedDate);
    const container = taskContainer.value;

    if (targetElement && container) {
      const containerTop = container.getBoundingClientRect().top;
      const targetTop = targetElement.getBoundingClientRect().top;

      // ➤ 计算目标元素相对容器顶部的偏移量
      const scrollOffset = targetTop - containerTop + container.scrollTop - 20;

      container.scrollTo({
        top: scrollOffset,
        behavior: 'smooth',
      });
    }
  });
};


onMounted(() => {
  getAllTask();
});

// 监听变化并更新 store
watch(reportFlag, (newValue: ReportFlag) => {
  reportStore.setReportFlag(newValue)
})
</script>
<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 100px);
  background-color: #ececec;
  font-family: 'PingFang SC', 'Segoe UI', sans-serif;
  padding: 20px;
  box-sizing: border-box;
  gap: 20px;
}

/* 顶部按钮 */
.top-header {
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 下方左右结构 */
.content-area {
  display: flex;
  flex: 1;
  gap: 20px;
  overflow: hidden;
}

/* 左：日历 */
.calendar-panel {
  flex: 1;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.calendar-panel::before {
  content: "📅 日历选择";
  display: block;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.calendar-panel p {
  margin: 6px 0;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  font-size: 14px;
  border: 1px solid transparent;
}

.calendar-panel p:hover {
  background-color: #f4f8fb;
  box-shadow: 0 0 6px rgba(64, 158, 255, 0.1);
}

.is-selected {
  color: rgb(110, 78, 208)
}

.is-today {
  border: 1px dashed #409eff;
}

.task-count-label {
  font-size: 12px;
  margin-top: 4px;
  color: #606266;
  display: block;
}

/* 右：任务报告 */
.report-panel {
  flex: 1;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.task-group {
  margin-bottom: 20px;
}

.task-date {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 12px;
  color: #333;
  top: 0;
  background: #fff;
  z-index: 2;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.date-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 14px;
  padding: 6px 2px;
  box-sizing: border-box;
  cursor: pointer;
}

.date-number {
  font-size: 16px;
  font-weight: bold;
}

.task-count {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
  line-height: 1.2;
  white-space: nowrap;
}


.task-table {
  width: 100%;
  table-layout: fixed;
  border-collapse: separate;
  border-spacing: 0 10px;
}

.task-table td {
  padding: 10px 12px;
  background-color: #fff;
  border-radius: 6px;
  text-align: center;
  vertical-align: middle;
  word-break: break-word;
  border: 1px solid #ebeef5;
  font-size: 14px;
}

.task-table tr td:first-child {
  width: 40px;
  text-align: center;
  font-weight: 500;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .content-area {
    flex-direction: column;
  }
}

.filter-item {
    min-width: 200px;
    
    &:deep(.el-input__inner) {
      height: 36px;
      line-height: 36px;
    }
  }

</style>